<template>
  <div class="flex items-center space-x-2">
    <button
      v-for="mode in themeModes"
      :key="mode"
      @click="setTheme(mode)"
      :class="[
        'p-2 rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary',
        currentTheme === mode ? 'bg-primary text-white' : 'bg-gray-200 dark:bg-gray-700'
      ]"
    >
      <component :is="icons[mode]" class="w-5 h-5" />
    </button>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ThemeMode, getCurrentTheme, setTheme } from '@/utils/theme'

// 图标组件
import { SunIcon, MoonIcon, ComputerDesktopIcon } from '@heroicons/vue/24/solid'

const icons = {
  [ThemeMode.LIGHT]: SunIcon,
  [ThemeMode.DARK]: MoonIcon,
  [ThemeMode.SYSTEM]: ComputerDesktopIcon
}

const themeModes = Object.values(ThemeMode)
const currentTheme = ref(getCurrentTheme())

watch(currentTheme, (newTheme) => {
  setTheme(newTheme)
})

onMounted(() => {
  // 监听系统主题变化
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
    if (currentTheme.value === ThemeMode.SYSTEM) {
      setTheme(ThemeMode.SYSTEM)
    }
  })
})
</script>